<template>
  <div id="app">
    <h1>购物车</h1>
    
    <div v-if="cartItems.length === 0" class="empty-cart">
      购物车是空的
    </div>
    
    <div v-else>
      <cart-item 
        v-for="item in cartItems" 
        :key="item.id" 
        :item="item"
      />
      
      <div class="total-price">
        总价：¥{{ totalPrice }}
      </div>
      
      <div class="add-item">
        <select v-model="newItem.id">
          <option value="1">手机</option>
          <option value="2">电脑</option>
          <option value="3">键盘</option>
        </select>
        <button @click="addItem">添加商品</button>
      </div>
    </div>
  </div>
</template>

<script>
import CartItem from './components/CartItem.vue'

export default {
  components: {
    CartItem
  },
  data() {
    return {
      newItem: {
        id: '1',
        name: '',
        price: 0
      },
      itemsData: {
        '1': { name: '手机', price: 1000 },
        '2': { name: '电脑', price: 2000 },
        '3': { name: '键盘', price: 200 }
      }
    }
  },
  computed: {
    cartItems() {
      return this.$store.state.cartItems
    },
    totalPrice() {
      return this.$store.getters.totalPrice
    }
  },
  methods: {
    addItem() {
      const selectedItem = this.itemsData[this.newItem.id]
      this.$store.dispatch('addItem', {
        id: parseInt(this.newItem.id),
        name: selectedItem.name,
        price: selectedItem.price
      })
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.total-price {
  font-weight: bold;
  text-align: right;
  margin-top: 20px;
  font-size: 1.2em;
}

.empty-cart {
  text-align: center;
  padding: 20px;
  color: #999;
}

.add-item {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}
</style>